<template>
  <view class="exchange-rate-container">
    <view class="calculator-card">
      <!-- 源货币部分 -->
      <view class="currency-row">
        <!-- 左侧货币信息 -->
        <view class="currency-info-left" @click="showCurrencySelector('source')">
          <view class="currency-avatar">
            <image 
              class="currency-icon" 
              :src="sourceCurrency.icon || '/static/images/default-currency.png'" 
              mode="aspectFit"
              @error="handleIconError($event)"
            />
          </view>
          <view class="currency-details">
            <text class="currency-code">{{ sourceCurrency.code || 'BTC' }}</text>
            <text class="currency-name">{{ sourceCurrency.name || '比特币' }}</text>
          </view>
          <view class="arrow-down">
            <text>▼</text>
          </view>
        </view>
        
        <!-- 右侧数值输入 -->
        <view class="amount-input-wrapper">
          <input 
            class="amount-input"
            type="digit"
            v-model="sourceAmount" 
            placeholder="1"
            @input="onSourceAmountChange"
            @focus="focusType = 'source'"
          />
        </view>
      </view>
      
      <!-- 交换按钮 -->
      <view class="exchange-btn-wrapper">
        <view class="exchange-btn" @click="swapCurrencies">
          <text class="swap-icon">⇅</text>
        </view>
      </view>
      
      <!-- 目标货币部分 -->
      <view class="currency-row">
        <!-- 左侧货币信息 -->
        <view class="currency-info-left" @click="showCurrencySelector('target')">
          <view class="currency-avatar">
            <image 
              class="currency-icon" 
              :src="targetCurrency.icon || '/static/images/default-currency.png'" 
              mode="aspectFit"
              @error="handleIconError($event)"
            />
          </view>
          <view class="currency-details">
            <text class="currency-code">{{ targetCurrency.code || 'USD' }}</text>
            <text class="currency-name">{{ targetCurrency.name || '美元' }}</text>
          </view>
          <view class="arrow-down">
            <text>▼</text>
          </view>
        </view>
        
        <!-- 右侧数值输入 -->
        <view class="amount-input-wrapper">
          <input 
            class="amount-input"
            type="digit"
            v-model="targetAmount" 
            placeholder="0"
            @input="onTargetAmountChange"
            @focus="focusType = 'target'"
          />
        </view>
      </view>
      
      <!-- 汇率信息 -->
      <view class="rate-info" v-if="exchangeRate && sourceCurrency.code && targetCurrency.code">
        <text class="rate-text">
          1 {{ sourceCurrency.code }} = {{ formatRate(exchangeRate) }} {{ targetCurrency.code }}
        </text>
        <text class="rate-time" v-if="lastUpdateTime">
          {{ lastUpdateTime }}
        </text>
      </view>
    </view>
    
    <!-- 货币选择弹窗组件 -->
    <currency-selector 
      :show="showSelector"
      :selector-type="selectorType"
      :selected-currency="selectorType === 'source' ? sourceCurrency : targetCurrency"
      @close="closeSelector"
      @select="onCurrencySelect"
    ></currency-selector>
  </view>
</template>

<script>
import currencySelector from '@/components/currencySelector.vue';
	import {gettickers} from '@/api/user.js'

export default {
  components: {
    currencySelector
  },
  data() {
    return {
      // 金额
      sourceAmount: '1',
      targetAmount: '',
      
      // 选中的货币（默认BTC和USD）
      sourceCurrency: {
        id: 1,
        code: 'BTC',
        name: '比特币',
        type: 0,
        icon: 'https://img.528btc.com.cn/pro/2023-10-26/img/1698308107894b782766bax1909c7242c830a44bcax54.jpg'
      },
      targetCurrency: {
        id: 3,
        code: 'USDT',
        name: '泰达币',
        type: 0,
        icon: 'https://img.528btc.com.cn/pro/2023-10-26/img/16983082055491a88a603448xj218aj1673130b212bbc.jpg'
      },
      
      // 汇率
      exchangeRate: null,
      
      // 货币选择器状态
      showSelector: false,
      selectorType: 'source', // 'source' 或 'target'
      
      // 当前聚焦的输入框
      focusType: 'source',
      
      // 最后更新时间
      lastUpdateTime: '',
      
      // 防止循环计算的标志
      isCalculating: false
    };
  },
  mounted() {
    // 组件挂载时初始化
    this.initDefaultExchange();
  },
  activated() {
    // 页面激活时重新获取汇率
    this.getExchangeRate();
  },
  methods: {
    // 初始化默认换算
    initDefaultExchange() {
      this.sourceAmount = '1';
      this.getExchangeRate();
    },
    
    // 显示货币选择器
    showCurrencySelector(type) {
      this.selectorType = type;
      this.showSelector = true;
    },
    
    // 关闭货币选择器
    closeSelector() {
      this.showSelector = false;
    },
    
    // 处理源货币金额变化
    onSourceAmountChange() {
      if (this.isCalculating) return;
      this.focusType = 'source';
      this.debounceCalculateFromSource();
    },
    
    // 处理目标货币金额变化
    onTargetAmountChange() {
      if (this.isCalculating) return;
      this.focusType = 'target';
      this.debounceCalculateFromTarget();
    },
    
    // 防抖计算（从源货币）
    debounceCalculateFromSource() {
      clearTimeout(this._calculateTimer);
      this._calculateTimer = setTimeout(() => {
        this.calculateFromSource();
      }, 300);
    },
    
    // 防抖计算（从目标货币）
    debounceCalculateFromTarget() {
      clearTimeout(this._calculateTimer);
      this._calculateTimer = setTimeout(() => {
        this.calculateFromTarget();
      }, 300);
    },
    
    // 从源货币计算目标货币
    calculateFromSource() {
      if (this.isCalculating || !this.exchangeRate || !this.sourceAmount) return;
      
      this.isCalculating = true;
      try {
        const result = (parseFloat(this.sourceAmount) * this.exchangeRate).toFixed(6);
        this.targetAmount = this.formatAmount(result);
      } catch (error) {
        console.error('计算出错:', error);
      } finally {
        this.isCalculating = false;
      }
    },
    
    // 从目标货币计算源货币
    calculateFromTarget() {
      if (this.isCalculating || !this.exchangeRate || !this.targetAmount) return;
      
      this.isCalculating = true;
      try {
        const result = (parseFloat(this.targetAmount) / this.exchangeRate).toFixed(8);
        this.sourceAmount = this.formatAmount(result);
      } catch (error) {
        console.error('计算出错:', error);
      } finally {
        this.isCalculating = false;
      }
    },
    
    // 格式化金额显示
    formatAmount(amount) {
      if (!amount || isNaN(amount)) return '';
      const num = parseFloat(amount);
      if (num === 0) return '0';
      if (num < 0.000001) return num.toExponential(2);
      if (num < 1) return num.toFixed(8).replace(/\.?0+$/, '');
      if (num < 1000) return num.toFixed(6).replace(/\.?0+$/, '');
      return num.toLocaleString(undefined, { maximumFractionDigits: 2 });
    },
    
    // 格式化汇率显示
    formatRate(rate) {
      if (!rate || isNaN(rate)) return '0';
      const num = parseFloat(rate);
      if (num < 0.000001) return num.toExponential(2);
      if (num < 1) return num.toFixed(8).replace(/\.?0+$/, '');
      if (num < 1000) return num.toFixed(6).replace(/\.?0+$/, '');
      return num.toLocaleString(undefined, { maximumFractionDigits: 2 });
    },
    
    // 处理图标加载失败
    handleIconError(e) {
      e.target.src = '/static/images/default-currency.png';
    },
    
    // 选择货币后回调
    onCurrencySelect(currency) {
      this.showSelector = false;
      
      console.log('接收到选中货币:', currency);
      
      // 确保货币数据包含必要字段
      if (!currency.id || typeof currency.type === 'undefined') {
        console.error('货币数据格式错误:', currency);
        uni.showToast({
          title: '货币数据错误',
          icon: 'none'
        });
        return;
      }
      
      const oldSourceCurrency = { ...this.sourceCurrency };
      const oldTargetCurrency = { ...this.targetCurrency };
      
      if (this.selectorType === 'source') {
        this.sourceCurrency = currency;
      } else {
        this.targetCurrency = currency;
      }
      
      // 发出货币变化事件
      this.$emit('currency-change', {
        type: this.selectorType,
        oldCurrency: this.selectorType === 'source' ? oldSourceCurrency : oldTargetCurrency,
        newCurrency: currency,
        sourceCurrency: this.sourceCurrency,
        targetCurrency: this.targetCurrency
      });
      
      // 获取新的汇率并计算
      this.getExchangeRate();
    },
    
    // 交换货币
    swapCurrencies() {
      const oldSourceCurrency = { ...this.sourceCurrency };
      const oldTargetCurrency = { ...this.targetCurrency };
      
      // 交换货币
      const temp = { ...this.sourceCurrency };
      this.sourceCurrency = { ...this.targetCurrency };
      this.targetCurrency = temp;
      
      // 交换金额
      const tempAmount = this.sourceAmount;
      this.sourceAmount = this.targetAmount;
      this.targetAmount = tempAmount;
      
      // 发出货币交换事件
      this.$emit('currency-change', {
        type: 'swap',
        oldSourceCurrency: oldSourceCurrency,
        oldTargetCurrency: oldTargetCurrency,
        sourceCurrency: this.sourceCurrency,
        targetCurrency: this.targetCurrency
      });
      
      // 获取新的汇率
      this.getExchangeRate();
    },
    
    // 获取汇率
    async getExchangeRate() {
      if (!this.sourceCurrency.id || !this.targetCurrency.id) {
        console.warn('货币信息不完整，无法获取汇率:', {
          source: this.sourceCurrency,
          target: this.targetCurrency
        });
        return;
      }
      
      console.log('获取汇率参数:', {
        sourceId: this.sourceCurrency.id,
        sourceType: this.sourceCurrency.type,
        targetId: this.targetCurrency.id,
        targetType: this.targetCurrency.type
      });
      
      try {
        const params = {
          param: {
            action: "currencyRate",
            "data[sourceId]": this.sourceCurrency.id,
            "data[sourceType]": this.sourceCurrency.type,
            "data[targetId]": this.targetCurrency.id,
            "data[targetType]": this.targetCurrency.type
          },
          c: "app",
          m: "v2"
        };
        
        const result = await gettickers(params);
        console.log('汇率接口返回:', result);
        
        if (result && result.success && result.data) {
          const newRate = result.data.data ? result.data.data.rate : result.data.rate;
          const oldRate = this.exchangeRate;
          this.exchangeRate = newRate;
          
          // 更新时间
          this.lastUpdateTime = this.formatUpdateTime(new Date());
          
          // 根据当前聚焦的输入框计算
          if (this.focusType === 'source' && this.sourceAmount) {
            this.calculateFromSource();
          } else if (this.focusType === 'target' && this.targetAmount) {
            this.calculateFromTarget();
          } else if (this.sourceAmount) {
            // 默认从源货币计算
            this.calculateFromSource();
          }
          
          // 发出汇率更新事件
          this.$emit('rate-update', {
            rate: newRate,
            oldRate: oldRate,
            sourceCurrency: this.sourceCurrency,
            targetCurrency: this.targetCurrency,
            timestamp: new Date().getTime()
          });
        } else {
          console.error('汇率获取失败:', result);
          uni.showToast({
            title: '获取汇率失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取汇率出错:', error);
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    },
    
    // 格式化更新时间
    formatUpdateTime(date) {
      const now = new Date();
      const diffMs = now - date;
      const diffMins = Math.floor(diffMs / 60000);
      
      if (diffMins < 1) return '刚刚更新';
      if (diffMins < 60) return `${diffMins}分钟前更新`;
      
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}更新`;
    }
  }
};
</script>

<style scoped>
.exchange-rate-container {
  display: flex;
  flex-direction: column;
  padding: 20rpx;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.calculator-card {
  background-color: #fff;
  border-radius: 24rpx;
  padding: 40rpx 30rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
  border: 1rpx solid #f0f0f0;
}

/* 货币行布局 */
.currency-row {
  display: flex;
  align-items: center;
  padding: 25rpx 20rpx;
  background: #fafbfc;
  border-radius: 16rpx;
  border: 2rpx solid #f0f0f0;
  transition: all 0.3s ease;
}

.currency-row:hover {
  border-color: #007aff;
  background: #f8fbff;
}

.currency-row:first-child {
  margin-bottom: 20rpx;
}

.currency-row:last-child {
  margin-top: 20rpx;
}

/* 左侧货币信息 */
.currency-info-left {
  display: flex;
  align-items: center;
  flex: 1;
  cursor: pointer;
  padding: 10rpx;
  border-radius: 12rpx;
  transition: background 0.2s ease;
}

.currency-info-left:hover {
  background: rgba(0, 122, 255, 0.05);
}

.currency-avatar {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  overflow: hidden;
  background: #fff;
  border: 2rpx solid #e8e9ea;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.currency-icon {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.currency-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.currency-code {
  font-size: 32rpx;
  font-weight: 600;
  color: #1a1a1a;
  line-height: 1.2;
}

.currency-name {
  font-size: 24rpx;
  color: #8e8e93;
  margin-top: 4rpx;
  line-height: 1.2;
}

.arrow-down {
  margin-left: 15rpx;
  color: #c7c7cc;
  font-size: 20rpx;
  transition: transform 0.2s ease;
}

.currency-info-left:hover .arrow-down {
  transform: translateY(2rpx);
}

/* 右侧金额输入 */
.amount-input-wrapper {
  flex: 1;
  max-width: 300rpx;
  margin-left: 20rpx;
}

.amount-input {
  width: 100%;
  text-align: right;
  font-size: 28rpx;
  font-weight: 600;
  color: #1a1a1a;
  border: none;
  outline: none;
  background: transparent;
  padding: 10rpx 0;
}

.amount-input::-webkit-input-placeholder {
  color: #c7c7cc;
  font-weight: 400;
}

/* 交换按钮 */
.exchange-btn-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 30rpx 0;
  position: relative;
}

.exchange-btn-wrapper::before {
  content: '';
  position: absolute;
  width: 100%;
  height: 1rpx;
  background: linear-gradient(90deg, transparent, #e8e9ea 20%, #e8e9ea 80%, transparent);
  z-index: 1;
}

.exchange-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80rpx;
  height: 80rpx;
  background: linear-gradient(135deg, #007aff, #005bb5);
  border-radius: 50%;
  box-shadow: 0 8rpx 20rpx rgba(0, 122, 255, 0.3);
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 2;
  position: relative;
}

.exchange-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 12rpx 24rpx rgba(0, 122, 255, 0.4);
}

.exchange-btn:active {
  transform: scale(0.95);
}

.swap-icon {
  font-size: 32rpx;
  color: #fff;
  font-weight: bold;
  transform: rotate(90deg);
}

/* 汇率信息 */
.rate-info {
  margin-top: 40rpx;
  padding: 30rpx;
  background: linear-gradient(135deg, #f8fbff, #f0f8ff);
  border-radius: 16rpx;
  border: 1rpx solid #e3f2fd;
  text-align: center;
}

.rate-text {
  font-size: 30rpx;
  font-weight: 500;
  color: #1565c0;
  display: block;
  margin-bottom: 8rpx;
}

.rate-time {
  font-size: 24rpx;
  color: #757575;
  opacity: 0.8;
}

/* 响应式调整 */
@media (max-width: 750rpx) {
  .calculator-card {
    padding: 30rpx 20rpx;
  }
  
  .currency-row {
    padding: 20rpx 15rpx;
  }
  
  .amount-input {
    font-size: 28rpx;
  }
  
  .currency-avatar {
    width: 56rpx;
    height: 56rpx;
  }
  
  .currency-code {
    font-size: 28rpx;
  }
  
  .currency-name {
    font-size: 22rpx;
  }
}
</style>
